// pages/transfer/tansferCake/tansferCake.js
const dayjs = require('dayjs')
import { getWarehouseProductList, getOrderStatistics, sally, outbound, finish, getExtractCode } from "../../../api/tansfer";
import Dialog from '@vant/weapp/dialog/dialog';
import Notify from '@vant/weapp/notify/notify';
const {getLocation} = require('../../../utils/map.js')

const codeTypeMap = {
  'out': '提取码出库',
  'finish': '提取码送达',
}

Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    showDateSelct: false,
    timeStart: dayjs().format('YYYY-MM-DD 00:00:00'),
    timeEnd: dayjs().add(1, 'day').format('YYYY-MM-DD 00:00:00'),
    activeCards: ['1', '2', '3'],
    outedList: [],
    unoutedList: [],
    statisList: [],
    codeDialog: {
      type: '',
      visible: false,
      title: '',
      
    },
    extractCode: ''
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onDateShow() {
      this.setData({showDateSelct: true})
      this.showDateSelct = true
    },
    onDateClose() {
      this.setData({showDateSelct: false})
      this.showDateSelct = false
    },
    onDateConfirm(event) {
      const [start, end] = event.detail;
      console.log(event)
      this.setData({
        showDateSelct: false,
        dateValue: `${dayjs(start).format('MM.DD HH:mm')} - ${dayjs(end).format('MM.DD HH:mm')}`
      });
    },
    onCardChange(event) {
      this.setData({
        activeCards: event.detail
      })
    },
    loadData() {
      this.getWarehouseProductList(1)
      this.getWarehouseProductList(2)
      this.getOrderStatistics()
    },
    // 获取已出库蛋糕列表
    getWarehouseProductList(type) {
      const { timeStart, timeEnd } = this.data
      return getWarehouseProductList({
        timeStart: timeStart,
        timeEnd: timeEnd,
        type
      }).then(res => {
        console.log(res);
        this.setWarehouseData({type, result: res.data.result || []})
      });
    },
    // 设置蛋糕列表
    setWarehouseData({type, result = []}) {
      const dataList = Object.keys(result).map(key => {
        return {
          name: key,
          text: result[key].length || 0,
          list: result[key],
          type,
        };
      })
      if (type == 1) {
        this.setData({
          outedList: dataList,
        })
      } else if (type == 2) {
        this.setData({
          unoutedList: dataList,
        })
      }
    },
    // 获取统计数据
    getOrderStatistics() {
      const { timeStart, timeEnd } = this.data
      return getOrderStatistics({
        timeStart: timeStart,
        timeEnd: timeEnd,
      }).then(res => {
        if (res.data && res.data.result) {
          this.setData({
            statisList: Object.keys(res.data.result).map(key => {
              const val = res.data.result[key];
              return {
                name: key,
                text: `${val['3']} / ${val['2']} / ${val['1']}`,
              };
            }),
          });
        } else {
          this.setData({
            statisList: [],
          });
        }
      });
    },
    handledDateRange(event) {
      const {start, end} = event.detail
      this.setData({
        timeStart: start,
        timeEnd: end
      })
      console.log(start, end)
    },
    // 扫描
    scanDispatch(event) {
      const {type} = event.currentTarget.dataset
      wx.scanCode({
        success: (res) => {
          var result = res.result;
          console.log(result)
          try {
            var parseJson = JSON.parse(result);
            const orderDetailId = (parseJson && parseJson.orderDetailId) || parseJson
            if (orderDetailId) {
              if (type === 'outbound') {
                this.handleScanOut(orderDetailId)
              } else if (type === 'finish') {
                this.handleScanFinish(orderDetailId)
              }
            } else {
              Notify({
                message: '获取单号失败，请重试扫描二维码',
                type: 'danger'
              })
            }
            
          } catch (error) {
            Notify({
              message: '扫描失败，请重试扫描二维码',
              type: 'danger'
            })
          }
        },
        fail: (e) => {
          console.log(e)
          Notify({
            message: '扫描失败，请重试扫描二维码',
            type: 'danger'
          })
        }
      })
      console.log(event)
    },
    // 出库
    async handleScanOut(orderDetailId) {
      const { longitude, latitude } = await getLocation()
      return outbound({
        orderDetailId: orderDetailId,
        longitude,
        latitude,
      })
        .then(res => {
          if (res.data.code == 200) {
            Notify({
              message: '出库成功',
              type: 'success'
            })
            this.loadData()
          } else {
            Notify({
              message: res.data.msg || '出库失败，请重试',
              type: 'danger'
            })
          }
        })
        .catch(err => {
          Notify({
            message: err.msg || '出库失败，请重试',
            type: 'danger'
          })
        })
    },
    // 送达
    async handleScanFinish(orderDetailId) {
      const { longitude, latitude } = await getLocation()
      return finish({
        orderDetailId: orderDetailId,
        longitude,
        latitude,
      })
        .then(res => {
          console.log(res)
          if (res.data && res.data.code == 200) {
            Notify({
              message: '送达成功',
              type: 'success'
            })
            this.loadData()
          } else {
            Notify({
              message: res.data.msg || '送达失败，请重试',
              type: 'danger'
            })
          }
        })
        .catch(err => {
          Notify({
            message: err.msg || '送达失败，请重试',
            type: 'danger'
          })
        })
    },
    // 出发
    sally() {
      Dialog.confirm({
        title: '提示',
        message: '请确认是否出发？',
      })
        .then(() => {
          // on confirm
          sally().then(res => {
            if (res.data.code == 200) {
              Notify({
                message: `出发成功`,
                type: 'success'
              })
              this.loadData()
            } else {
              Notify({
                message: `${res.data.msg}`,
                type: 'danger'
              })
            }
          })
        })
        .catch(() => {
          // on cancel
        });
    },
    // 打开提取码页面
    openCodeDialogPage(event) {
      const {type} = event.currentTarget.dataset
      this.setData({
        codeDialog: {
          type,
          visible: true,
          title: codeTypeMap[type],
        }
      })
    },
    // 提取码处理
    async handleCodeConfirm() {
      if (!this.data.extractCode) {
        wx.showToast({
          title: '请输入提取码',
          icon: 'none'
        })
        return
      }
      this.closeCodeDialog()
      const { type } = this.data.codeDialog
      const codeRes = await getExtractCode({code: this.data.extractCode})
      const data = codeRes.data && codeRes.data.result
      
      if (!data || !data.orderDetailId) {
        Notify({
          message: codeRes.data.msg || '提取码解析失败，请重试',
          type: 'danger'
        })
        return
      }
      if (type === 'out') {
        this.handleScanOut(data.orderDetailId)
      } else if (type === 'finish') {
        this.handleScanFinish(data.orderDetailId)
      }
    },
    handleCodeCancel() {
      this.closeCodeDialog()
    },
    closeCodeDialog() {
      this.setData({
        codeDialog: {
          ...this.data.codeDialog,
          visible: false
        }
      })
    },
    // 跳转蛋糕列表
    goCakeListPage(e) {
      const {item} = e.currentTarget.dataset
      console.log(item)
      wx.setStorageSync('transferCakeListPageItem', item)
      wx.navigateTo({
        url: '../transfer/transferCakeList/transferCakeList',
      })
    },
    // 页面相关事件处理函数
    onPullDownRefresh() {
      this.loadData()
      wx.stopPullDownRefresh()
    },
  },
  
  lifetimes: {
    attached: function() {
      wx.getLocation({
        success: (res) => {
          console.log(res)
        }
      })
      // 在组件实例进入页面节点树时执行
      const {timeStart, timeEnd} = this.data
      const dateRangeCom = this.selectComponent('#dateRange')
      dateRangeCom.setDefaultDate([timeStart, timeEnd])
      this.loadData()
    },
    detached: function() {
      // 在组件实例被从页面节点树移除时执行
    },
  },
})
